import 'package:distribution_mall_flutter/entity/pay/list/pay_list_entity.dart';
import 'package:distribution_mall_flutter/http/init.dart';
import 'package:distribution_mall_flutter/http/modules/pay.dart';
import 'package:distribution_mall_flutter/pages/home/state/app_info_state.dart';
import 'package:distribution_mall_flutter/provider/common/pay.dart';
import 'package:distribution_mall_flutter/utils/collection.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'pay_list_provider.g.dart';

@riverpod
class PayList extends _$PayList {
  @override
  List<PayListType> build() {
    return [];
  }

  ///获取支付方式
  Future<Result<PayListEntity>> getPayList(
      {required double? totalAmount, required bool? isCanCod}) async {
    var result = (await PayApi.getPaymentMethodsByOrderInfo({
      'currency': EPstorage.localCache.get(LocalCacheBoxKey.currency),
      'totalAmount': totalAmount,
      'isCanCod': isCanCod,
    }));
    if (result.hasSuccess) {
      state = result.data!.types;
    } else {
      state = [];
    }
    return result;
  }

  void setNewData(PayListEntity? paymentMethodList) {
    state = paymentMethodList?.types ?? [];
  }
}

extension ListPayListTypeToFormatType on List<PayListType> {
  ///获取修改后的数据模型
  List<FormatType> get formatPayList {
    List<FormatType> formatList = [];

    ///是否可显示(直接不显示)
    List<PayListType> list =
        where((PayListType type) => type.typeDisplayable == true).toList();

    ///支付方式类型列表
    for (PayListType item in list) {
      List<PaymentMethod> paymentMethodList = [];

      ///支付方式平台列表
      item.platforms?.forEach((platform) {
        // if(list.indexOf(item) == 0 || list.indexOf(item) == 1){
        //   platform.channels?.forEach((action){
        //     action.isUsable = false;
        //   });
        // }

        ///获取支付渠道,是否可显示(直接不显示)
        List<PaymentMethod> methodList = List.from(platform.channels
                ?.where((element) => element.displayable == true)
                .toList() ??
            []);

        ///排序一下
        methodList.sort((a, b) => a.isUsable == true ? -1 : 1);
        paymentMethodList.addAll(methodList);
      });

      ///需求:
      /// 1、支付方式（一级）下是否无任何可用支付渠道（二级），如果是，则该支付方式（一级）隐藏；
      /// 2、不是则展示全部改支付方式下支付渠道（二级），不可用的置灰；
      /// 3、是否有且只有一个支付方式的下一个支付渠道可用，如果是则默认选中此支付方式下支付渠道(这里不在这实现)
      if (paymentMethodList.isNotEmpty) {
        if (item.typeDisplayable == true && paymentMethodList.isNotEmpty) {
          /// 1、支付方式（一级）下是否无任何可用支付渠道（二级），如果是，则该支付方式（一级）隐藏；
          /// 2、不是则展示全部改支付方式下支付渠道（二级），不可用的置灰；
          bool usableIsNotEmpty = paymentMethodList
              .where((e) => e.displayable == true && e.isUsable == true)
              .isNotEmpty;
          if (usableIsNotEmpty) {
            ///转成自己想要的类
            FormatType formatType = FormatType();
            formatType.type = item.type;
            formatType.typeDisplay = item.typeDisplay;
            formatType.typeDisplayable = item.typeDisplayable;
            formatType.children = paymentMethodList;
            formatList.add(formatType);
          }
        }
      }
    }
    return formatList;
  }

  ///如果只有一个支付方式,那么就返回它不是一个就不返回
  PayMethodInfo? onlyOneCanUsePayMethod() {
    ///需求
    ///3、是否有且只有一个支付方式的下一个支付渠道可用，如果是则默认选中此支付方式下支付渠道
    var allCanUsePayMethod = CollectionUtils.mergeList<PaymentMethod>(
            formatPayList.map((e) => e.children))
        .where((e) => e.displayable == true && e.isUsable == true);
    println('allCanUsePayMethod ${allCanUsePayMethod.length}');

    ///判断是否只有一个支付方式
    bool isOnlySinglePayMethod = allCanUsePayMethod.length == 1;
    if (isOnlySinglePayMethod) {
      ///找到匹配的
      var type = formatPayList
          .firstWhere((e) => e.children.contains(allCanUsePayMethod.first));
      println('setPayMethodInfo ${allCanUsePayMethod.first.methodName}');
      return PayMethodInfo(
          type: type,
          paymentMethod: allCanUsePayMethod.first,
          methodCode: allCanUsePayMethod.first.methodCode!);
    }
    return null;
  }
}

///只是在支付选择页选择的支付方式
@riverpod
class SelectPayMethod extends _$SelectPayMethod {
  @override
  PayMethodInfo? build() {
    return null;
  }

  ///获取支付方式
  void setPayMethodInfo(PayMethodInfo? payMethodInfo) async {
    state = payMethodInfo;
  }
}

///支付方式列表展开
@riverpod
class PayListExpandedList extends _$PayListExpandedList {
  @override
  List<bool> build() {
    return [];
  }

  triggerExpanded(List<FormatType> formatPayList, int index, bool isExpanded) {
    ///formatPayList可以从ref读 但是目前不敢乱动
    int length = formatPayList.length;
    List<bool> list;
    list = List.generate(length, (i) {
      if (i == index) return isExpanded;
      return false;
    });
    state = list;
  }
}
